"""
认证依赖注入
"""
from typing import Optional
from fastapi import Depends, HTTPException, status, Cookie, Header
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials

from auth.jwt_handler import verify_token
from models.schemas import User


# HTTP Bearer认证方案（可选）
security = HTTPBearer(auto_error=False)


async def get_current_user(
    authorization: Optional[HTTPAuthorizationCredentials] = Depends(security),
    token: Optional[str] = Cookie(None)
) -> User:
    """
    获取当前用户
    支持两种方式传递Token：
    1. Authorization Header: Bearer {token}
    2. Cookie: token={token}
    
    Args:
        authorization: Authorization Header
        token: Cookie中的token
    
    Returns:
        当前用户信息
    
    Raises:
        HTTPException: 未授权或Token无效
    """
    # 优先从Cookie获取token
    token_str = token
    
    # 如果Cookie中没有，尝试从Authorization Header获取
    if not token_str and authorization:
        token_str = authorization.credentials
    
    if not token_str:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="未提供认证令牌",
            headers={"WWW-Authenticate": "Bearer"},
        )
    
    # 验证token
    payload = verify_token(token_str)
    if payload is None:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="认证令牌无效或已过期",
            headers={"WWW-Authenticate": "Bearer"},
        )
    
    # 从payload中提取用户信息
    username = payload.get("sub")
    if username is None:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="认证令牌格式错误",
            headers={"WWW-Authenticate": "Bearer"},
        )
    
    # 返回用户信息（这里是模拟数据）
    user = User(
        id=payload.get("user_id", 1),
        username=username,
        name=payload.get("name", "管理员"),
        role=payload.get("role", "admin")
    )
    
    return user
